<?php
namespace app\admin\controller;

date_default_timezone_set('PRC'); 
use think\Request;
use think\Controller;
use think\Model;
use think\Cookie;
use think\Session;

class Index extends Controller
{

    public function __construct(Request $request) {
        $url = $request->url(true);

        if ($url != $request->domain()."/admin" 
            && stripos($url,"loginCheck") == false
            && stripos($url,"loginOut") == false
            ) {
            $check = false;
            $starUser = Cookie::get('star_user');
            if ($starUser != null && !empty($starUser)) {
                $check = Session::has($starUser);
                if ($check) {
                    $status = Session::get($starUser);
                    if ($status) {
                        $check = true;
                    }
                }
            }
            if (!$check) {
                $this->redirect($request->domain()."/admin");
            }
        }
    }

    public function index()
    {
        return view('/login');
    }

    public function brand(Request $request)
    {
        $page = $request->get("page");
        $list = model("User")->getBrandList($page);
        return view('/brand',['list'=>$list]);
    }

    public function product(Request $request)
    {
        $serachBrandSelect = $request->get("serachBrandSelect");
        $page = $request->get("page");
        $list = model("User")->getProductList($page,$serachBrandSelect);
        $brandList = model("User")->getBrandSearhList();
        $jsonBrandList = json_encode($brandList);
        return view('/product',['list'=>$list,'brandList'=>$brandList,'jsonBlist'=>$jsonBrandList,'brandSerach'=>$serachBrandSelect]);
    }

    public function intention(Request $request)
    {
        $page = $request->get("page");
        $list = model("User")->getIntentionList($page);
        return view('/intention',['list'=>$list]);
    }

    public function loginCheck(Request $request) {
        if ($request->isPost() && $request->isAjax()) {
            $name = $request->post("name");
            $pwd = $request->post("pwd");

            if ($name == null || empty($name)) {
                $this->error("请输入Username!");
            }

            if ($pwd == null || empty($pwd)) {
                $this->error("请输入Password!");
            }

            $info = model("User")->getUserName($name);
            if ($info != null && !empty($info['name'])) {
                $checkKey = config("checkKey");
                $p = $pwd.$checkKey;
                if (md5($p) == $info['pwd']) {
                    $nameNew = base64_encode($name);
                    Cookie::set('star_user',$nameNew,3600*24);
                    Session::set($nameNew,'true');
                    $this->success("登陆成功",$request->domain()."/admin/index/brand");
                } else {
                    $this->error("密码有误!");
                }
            } else {
            $this->error("用户名有误！");
        }
            
        } else {
            $this->redirect($request->domain());
        }
    }

    public function logOut(Request $request) {
        $name = $request->post("name");
        $baseName = Cookie::get('star_user');
        Cookie::delete('star_user');
        Session::delete($baseName);
        $this->success("退出成功",$request->domain()."/admin");
    }

    public function addBrand(Request $request)
    {
        if ($request->isPost() && $request->isAjax()) {
            $file = $request->file('img'); 
            $name = $request->post("brandName");
            if (empty($file)) { 
                $this->error('请选择上传文件'); 
            } 
            $fileInfo = $file->getInfo();
            $type = $fileInfo['type'];
            if (!empty(strstr($type,"image/"))) {
                //移动到框架应用根目录/public/uploads/ 目录下 
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'); 
                if ($info) {
                    $resp = model("User")->addBrand($name,$info->getSaveName());
                    if ($resp) {
                        $this->success("图片上传成功！"); 
                    }
                } else { 
                    //上传失败获取错误信息 
                    $this->error($file->getError()); 
                } 
            } else {
                $this->error("图片格式有误！");
            }
            
        }
        $this->error("上传失败！");
    }

    public function delBrand(Request $request) {
        if ($request->isPost() && $request->isAjax()) {
            $id = $request->post('id'); 
            if ($id != null && !empty($id)) {
                $res = model("User")->delBrand($id);
                $this->success($res); 
            } else {
                $this->error("参数有误！");
            }
        }
    }

    public function setProduct(Request $request) {
        if ($request->isPost() && $request->isAjax()) {
            $params = array();
            $id = $request->post('id'); 
            $img = $request->file('img'); 
            $params['img'] = $this->getImgPath($img);
            $params['brand_id'] = $request->post('brandId'); 
            $params['name'] = trim($request->post('name'));
            $params['abstract'] = trim($request->post('abstract'));
            $params['is_hot'] = $request->post('isHot');
            $pic1 = $request->file('pic1'); 
            $params['pic1'] = $this->getImgPath($pic1);
            $params['star_price'] = trim($request->post('starPrice'));
            $params['guidance_price'] = trim($request->post('guidancePrice'));
            $params['discount'] = trim($request->post('discount'));
            $params['actual_price'] = trim($request->post('actualPrice'));

            $pic4 = $request->file('pic4'); 
            $params['pic4'] = $this->getImgPath($pic4);

            $file1 = $request->file('excel1');
            $pic2 = $request->file('pic2');
            $params['pic2'] = $this->getImgPath($pic2);
            $file2 = $request->file('excel2'); 

            $params['info'] = json_encode($this->getExcelDate($file1));
            $params['configure'] = json_encode($this->getExcelDate($file2));
            $pic3 = $request->file('pic3'); 
            $params['pic3'] = $this->getImgPath($pic3);
            if (isset($id) && $id != null && !empty($id)) {
                // 编辑
                $params['update_time'] = date('y-m-d h:i:s',time());
                $params['id'] = $id;
                $res = model("User")->updateProduct($id,$params);
                if ($res == 1) {
                    $this->success("编辑成功！");
                }
            } else {
                // 添加
                $params['add_time'] = date('y-m-d h:i:s',time());
                $res = model("User")->addProduct($params);
                $this->success("添加成功！");
            }
        }
        $this->error("操作失败！");
    }

    private function getExcelDate($file) {
        $data = array();
        vendor('PHPExcel.Classes.PHPExcel');

        $info = $file->validate(['ext' => 'xlsx,xls'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel');
        if(!empty($info)){
             //获取文件名
            $exclePath = $info->getSaveName();
            //上传文件的地址
            $filename = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel'. DS . $exclePath;
            //判断截取文件
            $extension = strtolower( pathinfo($filename, PATHINFO_EXTENSION) );

            //区分上传文件格式
            if($extension == 'xlsx') {
                $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
                $objPHPExcel = $objReader->load($filename, $encode = 'utf-8');
            }else if($extension == 'xls'){
                $objReader =\PHPExcel_IOFactory::createReader('Excel5');
                $objPHPExcel = $objReader->load($filename, $encode = 'utf-8');
            }
            //转换为数组格式
            $excel_array = $objPHPExcel->getsheet(0)->toArray();  

            //删除第一个数组(标题); 
            array_shift($excel_array);  
            
            if(is_array($excel_array) && count($excel_array) > 0) {
                foreach($excel_array as $k=>$v) {
                    if (isset($v[0]) && !empty($v[0]) && isset($v[1]) && !empty($v[1])) {
                        $data[trim($v[0])] = trim($v[1]);
                    }
                }
            }
        }
        return $data;
    }

    private function getImgPath($file) {
        $info = null;
        $path = "";
        $fileInfo = $file->getInfo();
        //移动到框架应用根目录/public/uploads/ 目录下 
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'); 
        if ($info) {
            $path = $info->getSaveName();
        }

        return $path;
    }

    public function getProdcut(Request $request) {
        if ($request->isPost() && $request->isAjax()) {
            $params = array();
            $id = $request->post('id');
            $info = model("User")->getProduct($id);
            $this->success("ok","",$info);
        }
    }

    public function delProduct(Request $request) {
        if ($request->isPost() && $request->isAjax()) {
            $params = array();
            $id = $request->post('id');
            $res = model("User")->delProduct($id);
            if ($res == 1) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    }

    public function delIntention(Request $request) {
        if ($request->isPost() && $request->isAjax()) {
            $params = array();
            $id = $request->post('id');
            $res = model("User")->delIntention($id);
            if ($res == 1) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    }
}
